﻿using System;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using easyccms.BusinessLayer;

namespace easyccms.Nhibernate
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ISession _session;

        public UnitOfWork()
        {
            _session = SessionProvider.OpenSession();
        }

        public void Dispose()
        {
            _session.Dispose();
        }

        public T Load<T>(int id)
        {
            return _session.Load<T>(id);
        }

        public IQueryable<T> GetList<T>()
        {
            return _session.Linq<T>();
        }

        public void Save(object entity)
        {
            
            if (_session.Transaction == null || !_session.IsOpen ) throw new Exception("The UnitOfWork did not have a current transaction.");
           _session.SaveOrUpdate(entity);
        }

        public void Delete(object entity)
        {
            _session.Delete(entity);
        }

        public void StartTransaction()
        {
            _session.BeginTransaction();
        }

        public void CommitTransaction()
        {
            
            if (_session.Transaction == null) throw new Exception("The UnitOfWork did not have a current transaction.");
            _session.Transaction.Commit();
        }

        public void RollbackTransaction()
        {
            if (_session.Transaction == null) throw new Exception("The UnitOfWork did not have a current transaction.");
            _session.Transaction.Rollback();
        }
    }
}